package com.yaorange.jk.service.impl;

import com.yaorange.jk.dao.BaseDao;
import com.yaorange.jk.entity.*;
import com.yaorange.jk.service.ContractProductService;
import com.yaorange.jk.service.ContractService;
import com.yaorange.jk.service.ExportProductService;
import com.yaorange.jk.service.ExportService;
import com.yaorange.jk.utils.Pagination;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author coach tam
 * @date 2017/11/1
 */
@Service("exportService")
@Transactional
public class ExportServiceImpl implements ExportService {


    @Autowired
    private BaseDao<Export,String> exportDao;

    @Autowired
    private ContractProductService contractProductService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private ExportProductService exportProductService;
    @Override
    @Transactional(readOnly = true)
    public Pagination findPage(int pageNo, int pageSize) {
        return exportDao.pageByHql("from Export",pageNo,pageSize);
    }


    @Override
    public List<Export> findAll() {
        return exportDao.getListByHQL("from Export");
    }

    @Override
    public void save(Export export) {
        //1,修改购销合同状态为2（报运状态）
        String[] contractIds = export.getId().split(", ");
        StringBuilder customerContract = new StringBuilder();//合同或确认书号
        for(String contractId:contractIds)
        {
            Contract contract = contractService.findById(contractId);
            customerContract.append(contract.getContractNo()).append(" ");
            contract.setState(2);
            contractService.update(contract);
        }

        //通过购销合同编号 查询到对应的货物列表（需要报运的购销合同中的所有货物列表）
        List<ContractProduct> cpList = contractProductService.findListByContractIds(contractIds);
        //2,新增报运单(货物，附件) ----》 数据搬家
        Set<ExportProduct> epSet = new HashSet<>(cpList.size());
        for(ContractProduct cp:cpList)
        {
            ExportProduct ep = new ExportProduct();
            //设置与报运单的关系
            ep.setExport(export);

            ep.setPrice(cp.getPrice());
            ep.setFactory(cp.getFactory());
            ep.setCnumber(cp.getCnumber());
            ep.setProductNo(cp.getProductNo());
            //购销合同货物附件集合
            Set<ExtCproduct> ecSet = cp.getExtCproducts();
            //       ||
            // copy  || 数据搬家，提升查询效率
            //       V V
            //报运货物附件集合
            Set<ExtEproduct> eeSet = new HashSet<>();
            for(ExtCproduct ec:ecSet){
                ExtEproduct ee = new ExtEproduct();
                //通过beanutils 拷贝数据  (购销合同货物附件)ec--->(报运货物附件)ee
                try {
                    BeanUtils.copyProperties(ee,ec);
                    ee.setId(null);
                    //设置 该报运附件 对应的 报运货物的关联关系
                    ee.setExportProduct(ep);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                //将报运附件添加到对应的报运附件集中
                eeSet.add(ee);
            }
            //设置报运货物 的 报运附件集合 （维护1-->N关系）
            ep.setExtEproducts(eeSet);
            //将报运货物添加到对应的报运货物集中
            epSet.add(ep) ;
        }

        //<set name="contractProducts" cascade="all" inverse="true">
        //因为1方不维护关系，所以我们需要通过多方设置关系
        export.setExportProducts(epSet);

        //3,设置报运合同编号，合同确认书号
        String s_contractIds = export.getId().replaceAll(" ","");
        export.setContractIds(s_contractIds);
        //TODO bug修复
        //1,修改报运单状态为0（报运草稿状态）
        // private Integer state;				//0-草稿 1-已上报 2-装箱 3-委托 4-发票 5-财务
        export.setState(0);
        export.setCustomerContract(customerContract.toString());
        exportDao.save(export);
    }

    @Override
    public Export findById(String id) {
        return exportDao.get(Export.class,id);
    }
    @Override
    public void update(Export model,
                       String[] mr_id, String[] mr_changed,
                       Integer[] mr_orderNo, Integer[] mr_cnumber,
                       Double[] mr_grossWeight, Double[] mr_netWeight,Double[] mr_sizeLength,
                       Double[] mr_sizeWidth, Double[] mr_sizeHeight, Double[] mr_exPrice, Double[] mr_tax) {
        exportDao.update(model);

        //更新货物信息
        for (int i = 0 ;i < mr_id.length;i++) {
            if("1".equals(mr_changed[i]))
            {
                ExportProduct ep = exportProductService.findById(mr_id[i]);
                ep.setCnumber(mr_cnumber[i]);
                ep.setSizeLength(mr_sizeLength[i]);
                ep.setTax(mr_tax[i]);
                ep.setSizeWidth(mr_sizeWidth[i]);
                ep.setSizeHeight(mr_sizeHeight[i]);
                ep.setNetWeight(mr_netWeight[i]);
                ep.setGrossWeight(mr_grossWeight[i]);
                ep.setOrderNo(mr_orderNo[i]);
                ep.setExPrice(mr_exPrice[i]);
                exportProductService.update(ep);
            }
        }
    }


    /**
     * 取消一个或一个以上的（已报运）报运单，--》草稿
     * @param id
     */
    @Override
    public void cancel(String id) {
        String[] ids = id.split(", ");
        for (String i : ids){
            exportDao.executeSql("update EXPORT_C SET STATE=? where EXPORT_ID = ?",0,i);
        }
    }
    /**
     * 上报一个或一个以上的（草稿）报运单，--》已上报
     * @param id
     */
    @Override
    public void submit(String id) {
        String[] ids = id.split(", ");
        for (String i : ids){
            exportDao.executeSql("update EXPORT_C SET STATE=? where EXPORT_ID = ?",1,i);
        }
    }

    @Override
    public void deleteByIds(String[] ids) {
        for (String id :ids)
        {
            exportDao.deleteById(Export.class,id);
        }
    }
}
